package com.lx.gulimall.order.service.impl;

import com.lx.gulimall.order.entity.OrderReturnReasonEntity;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lx.common.utils.PageUtils;
import com.lx.common.utils.Query;

import com.lx.gulimall.order.dao.OrderItemDao;
import com.lx.gulimall.order.entity.OrderItemEntity;
import com.lx.gulimall.order.service.OrderItemService;

@RabbitListener(queues = {"hello-java-queue"})
@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    /**
     *  queues:声明需要监听的所有队列
     *
     *  消息的类型：class org.springframework.amqp.core.Message
     *  参数可以写一下类型
     *      1.Message : 原生消息详细信息。头+体
     *      2.T<发送消息的类型> OrderReturnReasonEntity reasonEntity
     *      3.Channel channel ：当前传输数据的通道
     *
     *  3.Queue ：可以有很多人监听。只要收到信息，就会删除，那么就只有一个收到信息
     *    1）、订单服务启动多个（接听消息的）；同一个消息，只能有一个客户端收到
     *    2）、只有一个信息处理完成，才会再次处理下一个消息
     *
     */
    //@RabbitListener(queues = {"hello-java-queue"})
    @RabbitHandler
    public void receiveMessage(Message message,
                               OrderReturnReasonEntity reasonEntity,
                               Channel channel){
        System.out.println("接受的消息..."+message+" 内容... "+reasonEntity);

        // channel内按顺序自增的
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        System.out.println("DeliveryTag---->"+deliveryTag);

        // 签收货物，非批量模式
        try {
            if(deliveryTag%2==0){
                // long deliveryTag boolean multiple
                channel.basicAck(deliveryTag, false);
            }else {
                // 拒收，退货 requeue=false 丢弃  requeue=true 发回服务器，重新入队
                // long deliveryTag, boolean multiple, boolean requeue
                channel.basicNack(deliveryTag,false,true);
                // long deliveryTag, boolean requeue
                //channel.basicReject();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @RabbitHandler
    public void receiveMessage(OrderItemEntity orderItemEntity){
        System.out.println(" 内容... "+orderItemEntity);
    }

}